package com.hky.aiagent.tools;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 终端操作工具
 */
public class TerminalOperationTool {

    @Tool(description = "Execute a command in the terminal")

    public String executeTerminalCommand(@ToolParam(description = "Command to execute in the terminal") String command) {
        StringBuilder output = new StringBuilder();
        try {
            // 执行终端命令，并获取Process对象
//            Process process = Runtime.getRuntime().exec(command);
            ProcessBuilder builder = new ProcessBuilder("cmd.exe",  "/c", command);
            Process process = builder.start();

            // 使用BufferedReader读取命令输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                // 循环读取命令输出的每一行，并将其添加到StringBuilder中
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }

            // 等待命令执行完成，并获取退出码
            int exitCode = process.waitFor();
            // 如果退出码不为0，表示命令执行失败，追加错误信息
            if (exitCode != 0) {
                output.append("Command execution failed with exit code: ").append(exitCode);
            }
        } catch (IOException | InterruptedException e) {
            // 捕获可能出现的IOException或InterruptedException，追加异常信息
            output.append("Error executing command: ").append(e.getMessage());
        }
        // 返回最终的输出结果字符串
        return output.toString();
    }

}
